HopDongInfoFieldSet = Ext.extend(Ext.form.FieldSet, {
	readOnly : false,
	allowInputMaHd : true,
	autoHeight : true,
	height : 180,
	title : lang.text.hd.hdInfo,
	layout : 'column',
	isEdit : false,
	
	initComponent : function() {
		if (!this.readOnly) {
			var fieldPlugin = new CustomizedFieldPlugin();
			this.maHdTextField = new Ext.form.TextField({
				name : "maHd",
				fieldLabel : lang.text.hd.maHd,
				width : 180,
				selectOnFocus : true,
				style : {
					textTransform : 'uppercase'
				},
				autoCreate: {
		            tag: 'input', type: 'text', size: '20',
		            autocomplete: 'off', maxlength: '10'},
				allowBlank : false,
				mandatory : true,
				validator : !this.isEdit ? this.validateMaHd : null,
				plugins : fieldPlugin
			});
			
			this.doiTruongCombo = new Ext.form.ComboBox({
				name : 'nvDoiTruong',
				hiddenName : 'nvDoiTruong-id',
	            fieldLabel : lang.text.hd.doiTruong,
	            width : 250,
	            expandOnFocus : true,
	            forceSelection : true,
	            mode : 'local',
	            triggerAction : 'all',
	            valueField : 'id',
	            displayField : 'maNv',
	            store : new Ext.data.JsonStore({
	                fields : ['id', 'maNv']
	            }),
	            tpl:'<tpl for="."><div class="x-combo-list-item">{maNv}&nbsp;' + '</div></tpl>'
			});
			
			this.nvBan1Combo = new Ext.form.ComboBox({
				name : 'nvBan1',
				hiddenName : 'nvBan1-id',
	            fieldLabel : lang.text.hd.nvBan1,
	            width : 250,
	            editable : true,
	            expandOnFocus : true,
	            forceSelection : true,
	            mode : 'local',
	            triggerAction : 'all',
	            lastQuery : '',
	            valueField : 'id',
	            displayField : 'maNv',
	            store : new Ext.data.JsonStore({
	                fields : ['id', 'maNv', 'doiTruong-id']
	            }),
	            allowBlank : false,
				mandatory : true,
				plugins : fieldPlugin
			});
			
			this.nvBan2Combo = new Ext.form.ComboBox({
				name : 'nvBan2',
				hiddenName : 'nvBan2-id',
	            fieldLabel : lang.text.hd.nvBan2,
	            width : 250,
	            editable : true,
	            expandOnFocus : true,
	            forceSelection : true,
	            mode : 'local',
	            triggerAction : 'all',
	            lastQuery : '',
	            valueField : 'id',
	            displayField : 'maNv',
	            store : new Ext.data.JsonStore({
	                fields : ['id', 'maNv', 'doiTruong-id']
	            }),
	            allowBlank : false,
				mandatory : true,
				plugins : fieldPlugin
			});
			
			this.thuNganCombo = new Ext.form.ComboBox({
				name : 'nvThuNgan',
				hiddenName : 'nvThuNgan-id',
	            fieldLabel : lang.text.hd.thuNgan,
	            width : 250,
	            editable : true,
	            expandOnFocus : true,
	            forceSelection : true,
	            mode : 'local',
	            triggerAction : 'all',
	            valueField : 'id',
	            displayField : 'maNv',
	            store : new Ext.data.JsonStore({
	                fields : ['id', 'maNv']
	            })
			});
			
			this.ngayBanDateField = new ThienTanDateField({
				fieldLabel : lang.text.hd.ngayBan,
				width : 180,
				name: 'ngayBan',
				autoCreate: {
		            tag: 'input', type: 'text', size: '10',
		            autocomplete: 'off', maxlength: '6'},
				allowBlank : false,
				mandatory : true
			});
			
			var leftCtn = new Ext.Container({
				width : 250,
				labelWidth : 120,
				layout : 'customizedlayout',
				columnWidth: .5,
				items : [this.maHdTextField, this.doiTruongCombo, this.nvBan1Combo, 
				         this.nvBan2Combo, this.thuNganCombo, this.ngayBanDateField]
			});
			
			this.dotBanTextField = new Ext.ux.NumericField({
				name : "dotBan",
				fieldLabel : lang.text.hd.dotBan,
				width : 250,
				selectOnFocus : true,
				autoCreate: {
		            tag: 'input', type: 'text', size: '20',
		            autocomplete: 'off', maxlength: '12'},
				useThousandSeparator : true,
				allowNegative : false,
	            allowBlank : false,
				mandatory : true,
				plugins : fieldPlugin
			});
			
			this.giaTriTextField = new Ext.ux.NumericField({
				name : "giaTri",
				fieldLabel : lang.text.hd.tongTien,
				value : this.isEdit ? null : tt_default.hd.giaTriHd,
				width : 250,
				selectOnFocus : true,
				autoCreate: {
		            tag: 'input', type: 'text', size: '20',
		            autocomplete: 'off', maxlength: '12'},
				useThousandSeparator : true,
				allowNegative : false,
				unit : tt_default.hd.unit,
	            allowBlank : false,
				mandatory : true,
				plugins : fieldPlugin
			});
			
			this.thuTienNgayChkbox = new Ext.form.Checkbox({
		        autoDestroy : true,
		        name : 'thuTienNgay',
		        disabled : this.isEdit,
		        fieldLabel : lang.text.hd.thuTienNgay
		    });
			
			this.tienTraTruocTextField = new Ext.ux.NumericField({
				name : "tienTraTruoc",
				fieldLabel : lang.text.hd.traTruoc,
				value : this.isEdit ? null : tt_default.hd.traTruoc,
				width : 250,
				selectOnFocus : true,
				autoCreate: {
		            tag: 'input', type: 'text', size: '20',
		            autocomplete: 'off', maxlength: '12'},
				useThousandSeparator : true,
				allowNegative : false,
				unit : tt_default.hd.unit,
				allowBlank : false,
				mandatory : true,
				plugins : fieldPlugin
			});
			
			this.tienDaThuTextField = new Ext.ux.NumericField({
				name : "tienDaThu",
				fieldLabel : lang.text.hd.daThu,
				value : this.isEdit ? null : 0,
				width : 250,
				selectOnFocus : true,
				autoCreate: {
		            tag: 'input', type: 'text', size: '20',
		            autocomplete: 'off', maxlength: '12'},
				useThousandSeparator : true,
				allowNegative : false,
				unit : tt_default.hd.unit,
				allowBlank : false,
				mandatory : true,
				plugins : fieldPlugin
			});
			
			this.tienConLaiTextField = new Ext.form.DisplayField({
				name : "tienConLai",
				width : 250,
				style: 'text-align: right',
				unit : tt_default.hd.unit,
				value : this.isEdit ? null : Utility.formatThousandSeparator(tt_default.hd.giaTriHd - tt_default.hd.traTruoc),
				fieldLabel : lang.text.hd.conLai
			});
			
			var rightCtn = new Ext.Container({
				layout : 'customizedlayout',
				columnWidth: .5,
				labelWidth : 120,
				items : [this.dotBanTextField, this.giaTriTextField, this.thuTienNgayChkbox, 
				         this.tienTraTruocTextField, this.tienDaThuTextField, this.tienConLaiTextField]
			});
			this.calculatingInfoTextFields = [this.giaTriTextField, this.tienTraTruocTextField,
			                                  this.tienDaThuTextField, this.tienConLaiTextField];
			if (this.isEdit) {
				this.idHidden = new Ext.form.Hidden({
					name : 'id'
				});
				this.items = [this.idHidden, leftCtn, {xtype : 'spacer', width : 20}, rightCtn]
			} else {
				this.items = [leftCtn, {xtype : 'spacer', width : 20}, rightCtn]
			}
			
		} else {
			if (this.allowInputMaHd) {
				this.maHdTextField = new Ext.form.TextField({
					name : "maHd",
					fieldLabel : lang.text.hd.maHd,
					width : 180,
					style : {
						textTransform : 'uppercase'
					},
					allowBlank : false,
					mandatory : true,
					plugins : new CustomizedFieldPlugin()
				});
			} else {
				this.maHdTextField = new Ext.form.DisplayField({
					fieldLabel : lang.text.hd.maHd,
					width : 180
				});
			}
			
			this.doiTruongCombo = new Ext.form.DisplayField({
	            fieldLabel : lang.text.hd.doiTruong,
	            width : 250
			});
			
			this.nvBan1Combo = new Ext.form.DisplayField({
	            fieldLabel : lang.text.hd.nvBan1,
	            width : 250
			});
			
			this.nvBan2Combo = new Ext.form.DisplayField({
	            fieldLabel : lang.text.hd.nvBan2,
	            width : 250
			});
			
			this.thuNganCombo = new Ext.form.DisplayField({
	            fieldLabel : lang.text.hd.thuNgan,
	            width : 250
			});
			
			this.ngayBanDateField = new Ext.form.DisplayField({
				fieldLabel : lang.text.hd.ngayBan,
				width : 180
			});
			
			var leftCtn = new Ext.Container({
				labelWidth : 120,
				layout : 'customizedlayout',
				items : [this.maHdTextField, this.doiTruongCombo, this.nvBan1Combo, 
				         this.nvBan2Combo, this.thuNganCombo, this.ngayBanDateField]
			});
			
			this.giaTriTextField = new Ext.form.DisplayField({
				fieldLabel : lang.text.hd.tongTien,
				width : 180
			});
			
			this.tienTraTruocTextField = new Ext.form.DisplayField({
				width : 180,
				fieldLabel : lang.text.hd.traTruoc
			});
			
			this.tienDaThuTextField = new Ext.form.DisplayField({
				width : 180,
				fieldLabel : lang.text.hd.daThu
			});
			
			this.tienConLaiTextField = new Ext.form.DisplayField({
				width : 180,
				fieldLabel : lang.text.hd.conLai
			});
			
			this.trangThai = new Ext.form.DisplayField({
				width : 180,
				fieldLabel : lang.text.hd.trangThai
			});
			var rightCtn = new Ext.Container({
				layout : 'customizedlayout',
				labelWidth : 100,
				cls : 'field-align-right',
				items : [this.giaTriTextField, this.tienTraTruocTextField,
				         this.tienDaThuTextField, this.tienConLaiTextField, this.trangThai]
			});
			
			this.idHidden = new Ext.form.Hidden({
				name : 'id'
			});
			
			this.items = [this.idHidden, leftCtn, {xtype : 'spacer', width : 20}, rightCtn]
		}
		
		HopDongInfoFieldSet.superclass.initComponent.call(this);
	},
	
	afterRender : function() {
		this.maHdTextField.on('afterrender', function(){
			var f = this.maHdTextField.getEl();
            f.focus.defer(200, f);
		}, this);
		
		if (!this.readOnly) {
			if (this.isEdit) {
				this.maHdTextField.on('blur', this.requestHdInfo, this);				
			} else {
				this.ngayBanDateField.setValue(new Date());
				this.thuTienNgayChkbox.on('check', this.fillRelatedData, this);
				this.giaTriTextField.on('change', this.adaptChangeFromGiaTri, this);
				this.tienTraTruocTextField.on('change', this.adaptChangeFromTraTruoc, this);
				this.tienDaThuTextField.on('change', this.adaptChangeFromDaThu, this);
			}
			this.doiTruongCombo.on('select', this.resetNvCombo, this);
			this.nvBan1Combo.on('select', this.autoFillNvBan2, this);
			this.nvBan1Combo.on('expand', this.reloadNhanVien, this);
			this.nvBan2Combo.on('expand', this.reloadNhanVien, this);
		} else {
			this.maHdTextField.on('blur', this.requestHdInfo, this);
		}
		HopDongInfoFieldSet.superclass.afterRender.call(this);
	},
	
	resetNvCombo : function(combo) {
		this.nvBan1Combo.clearValue();
		this.nvBan2Combo.clearValue();
	},
	
	reloadNhanVien : function(combo) {
		if (combo.store.isFiltered()) {
			combo.store.clearFilter();
		}
		combo.clearValue();
		var value = this.doiTruongCombo.getValue()
		if (value != null && value != "") {
			combo.store.filterBy(function(record) {
				return record.get('doiTruong-id') == value;
			});
		}
	},
	
	validateMaHd : function(){
		this.clearInvalid();
		var maHd = this.getValue();
		if(maHd == null || maHd =="") {
			this.focus(true);
			return lang.msg.nhapMaHd
		}
		if(!new RegExp(lang.regexp.validateMaHd).test(maHd)) {
			this.focus(true);
			return lang.msg.invalidMaHd
		}
		return true
	},
	
	requestHdInfo : function(field) {
		if(this.readOnly) {
			this.resetInfo();
		}
		this.ownerCt.formMessage.hide();
		this.ownerCt.doLayout();
		if (this.ownerCt.beforeRequestHdInfo) {
			this.ownerCt.beforeRequestHdInfo();
		}
		var value = field.getValue();
		if (value == null || value == "") {
			return;
		}
		Ext.Ajax.request({
            url : 'hopDong/requestHdInfo',
            params : {
            	'maHd' : value,
            	'isEditHd' : this.isEdit
            },
            method : 'GET',
            scope : this,
            success : function(response, opts){
                var result = Ext.decode(response.responseText);
                if (result.success) {
                	this.storeHdInfoToObject(result.data);
                	this.loadHdInfoToForm(ApplicationManager.hdInfo);
                	if (this.ownerCt.loadMoreData) {
                		this.ownerCt.loadMoreData(result.data);
					}
                	if (this.ownerCt.afterRequestHdInfo) {
            			this.ownerCt.afterRequestHdInfo();
            		}
				} else {
					this.ownerCt.notifyMessage({action : "error", msg : result.msg})
					field.focus(true);
				}
            }, 
            failure : function() {}
        });
	},
	
	storeHdInfoToObject : function(responseData) {
		ApplicationManager.hdInfo = {
			id : responseData["id"],
			maHd : responseData["maHd"],
			doiTruong : responseData["nvDoiTruong-maNv"],
			nvBan1 : responseData["nvBan1-maNv"],
			nvBan2 : responseData["nvBan2-maNv"],
			thuNgan : responseData["nvThuNgan-maNv"],
			ngayBan : new Date(responseData["ngayBan"]).format("d-m-Y"),
			giaTri : responseData["giaTri"],
			tienTraTruoc : responseData["tienTraTruoc"],
			tienDaThu : responseData["tienDaThu"],
			tienConLai : responseData["tienConLai"],
			trangThai : responseData["trangThaiText"],
			daGiaoPhieu : responseData["daGiaoPhieu"]
		}
	},
	
	loadHdInfoToForm : function(hdInfo) {
		this.idHidden.setValue(hdInfo.id);
		this.maHdTextField.setValue(hdInfo.maHd);
    	this.doiTruongCombo.setValue(hdInfo.doiTruong);
    	this.nvBan1Combo.setValue(hdInfo.nvBan1);
    	this.nvBan2Combo.setValue(hdInfo.nvBan2);
    	this.thuNganCombo.setValue(hdInfo.thuNgan);
    	this.ngayBanDateField.setValue(hdInfo.ngayBan);
    	this.giaTriTextField.setValue(this.isEdit ? hdInfo.giaTri / 1000 : Utility.formatThousandSeparator(hdInfo.giaTri));
    	this.tienTraTruocTextField.setValue(this.isEdit ? hdInfo.tienTraTruoc / 1000 : Utility.formatThousandSeparator(hdInfo.tienTraTruoc));
    	this.tienDaThuTextField.setValue(this.isEdit ? hdInfo.tienDaThu / 1000 : Utility.formatThousandSeparator(hdInfo.tienDaThu));
    	this.tienConLaiTextField.setValue(this.isEdit ? hdInfo.tienConLai / 1000 : Utility.formatThousandSeparator(hdInfo.tienConLai));
    	if (!this.isEdit) {
    		this.trangThai.setValue(hdInfo.trangThai);
		}
	},
	
	autoFillNvBan2 : function(combo, record, index) {
		if(this.doiTruongCombo.getValue() == null || this.doiTruongCombo.getValue() == "") {
			this.nvBan2Combo.setValue(record.get("id"));
		}
	},
	
	fillRelatedData : function(chkbox, checked) {
		var giaTriHd = this.giaTriTextField.getValue();
		var tienTraTruoc = this.tienTraTruocTextField.getValue();
		if (checked) {
			if(giaTriHd == null || giaTriHd == "") {
				this.giaTriTextField.markInvalid({id : 'giaTri', action : 'error', msg : lang.msg.nhapGiaTriHd})
				this.giaTriTextField.focus();
				chkbox.setValue(false);
			} else {
				this.tienTraTruocTextField.setValue(giaTriHd);
				this.tienTraTruocTextField.disable();
				this.tienDaThuTextField.setValue(0);
				this.tienDaThuTextField.disable();
				this.tienConLaiTextField.setValue(0);
			}
		} else {
			if(giaTriHd != null || giaTriHd != "") {
				this.tienTraTruocTextField.enable();
				this.tienDaThuTextField.enable();
			}
		}
	},
	
	adaptChangeFromGiaTri : function(textField, newVal, oldVal) {
		if (this.thuTienNgayChkbox.checked) {
			this.tienTraTruocTextField.setValue(newVal);
			this.tienDaThuTextField.setValue(newVal);
		} else {
			var traTruoc = this.tienTraTruocTextField.getValue();
			var daThu = this.tienDaThuTextField.getValue();
			if (newVal < traTruoc + daThu) {
				textField.markInvalid({id : 'giaTri', action : 'error', msg : lang.msg.giaTriNhoHonTraTruocVaDaThu});
				return;
			} else {
				this.tienConLaiTextField.setValue(Utility.formatThousandSeparator(newVal - traTruoc - daThu));
			}
		}
	},
	
	adaptChangeFromTraTruoc : function(textField, newVal, oldVal) {
		var giaTriHd = this.giaTriTextField.getValue();
		if (giaTriHd == null || giaTriHd == "") {
			textField.markInvalid({id : 'tienTraTruoc', action : 'error', msg : lang.msg.nhapGiaTriHdFirst})
			return;
		}
		if (newVal > giaTriHd) {
			textField.markInvalid({id : 'tienTraTruoc', action : 'error', msg : lang.msg.exceedGiaTriHd})
			return;
		}
		var tienDaThu = this.tienDaThuTextField.getValue();
		this.tienConLaiTextField.setValue(Utility.formatThousandSeparator(giaTriHd - newVal - tienDaThu));
	},
	
	adaptChangeFromDaThu : function(textField, newVal, oldVal) {
		var giaTriHd = this.giaTriTextField.getValue();
		if (giaTriHd == null || giaTriHd == "") {
			textField.markInvalid({id : 'tienDathu', action : 'error', msg : lang.msg.nhapGiaTriHdFirst})
			return;
		}
		if (newVal > giaTriHd) {
			textField.markInvalid({id : 'tienDathu', action : 'error', msg : lang.msg.exceedGiaTriHd})
			return;
		}
		
		var tienTraTruoc = this.tienTraTruocTextField.getValue();
		if (newVal + tienTraTruoc > giaTriHd) {
			textField.markInvalid({id : 'tienDathu', action : 'error', msg : lang.msg.plusTraTruocExceedGiaTriHd})
			return;
		}
		if (newVal != null && newVal != "") {
			this.tienConLaiTextField.setValue(Utility.formatThousandSeparator(giaTriHd - newVal - tienTraTruoc));	
		}
	},
	
	resetInfo : function() {
		this.doiTruongCombo.setValue(null);
		this.nvBan1Combo.setValue(null);
		this.nvBan2Combo.setValue(null);
		this.thuNganCombo.setValue(null);
		this.ngayBanDateField.setValue(null);
		this.giaTriTextField.setValue(null);
		this.tienTraTruocTextField.setValue(null);
		this.tienDaThuTextField.setValue(null);
		this.tienConLaiTextField.setValue(null);
		this.trangThai.setValue(null);
		this.idHidden.setValue(null);
	}
});

Ext.override(Ext.form.ComboBox, {
	MAX_ITEM_NOT_FILTER : tt_default.itemsNotFilter,
    afterRender: function () {
    	Ext.form.ComboBox.superclass.afterRender.call(this);
    	this.tpl = '<tpl for="."><div class="x-combo-list-item">{' + this.displayField + '}&nbsp;' + '</div></tpl>'
    	this.mon(this.store, 'load', this.updateData, this);
    	if(this.expandOnFocus){
            this.on('focus',this.handleEditItem,this);
        }
    },
    
    handleEditItem : function(){
        this.onTriggerClick();
        this.setEditable(this.store.data.length > this.MAX_ITEM_NOT_FILTER);
    },
    
    updateData : function() {
    	if (this.addEmptyItemAtFirst && this.store.data.length > 0) {
    		var currentRecord = this.store.getAt(0);
            var itemAll = currentRecord.copy();
            var id = Ext.data.Record.id(itemAll);
            
            itemAll.id = id;
            itemAll.set(this.displayField, ' ');
            itemAll.set(this.valueField, '');        
            
            if (itemAll) {
            	this.store.insert(0,itemAll);
                this.setValue('');    
            }
		}
    	this.setEditable(this.store.data.length > this.MAX_ITEM_NOT_FILTER);
    }
});